package com.ruoyi.web.controller.common;

import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Date;
import java.util.concurrent.TimeUnit;
import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.kong.domain.KSbh;
import com.ruoyi.kong.mapper.KSbhMapper;
import com.ruoyi.kong.service.IKSbhService;
import com.ruoyi.socket.ws.WsSysMsg;
import com.ruoyi.socket.ws.bean.LoginVo;
import com.ruoyi.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.FastByteArrayOutputStream;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import com.google.code.kaptcha.Producer;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.constant.CacheConstants;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.sign.Base64;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.system.service.ISysConfigService;

/**
 * 验证码操作处理
 * 
 * @author ruoyi
 */
@RestController
public class CaptchaController
{
    @Resource(name = "captchaProducer")
    private Producer captchaProducer;

    @Resource(name = "captchaProducerMath")
    private Producer captchaProducerMath;

    @Autowired
    private RedisCache redisCache;
    
    @Autowired
    private ISysConfigService configService;

    @Autowired
    ISysUserService iSysUserService;

    @Autowired
    IKSbhService ikSbhService;

    @Autowired
    KSbhMapper kSbhMapper;
    /**
     * 生成验证码
     */
    @GetMapping("/captchaImage")
    public AjaxResult getCode(HttpServletResponse response) throws IOException
    {
        AjaxResult ajax = AjaxResult.success();
        boolean captchaEnabled = configService.selectCaptchaEnabled();
        ajax.put("captchaEnabled", captchaEnabled);
        if (!captchaEnabled)
        {
            return ajax;
        }

        // 保存验证码信息
        String uuid = IdUtils.simpleUUID();
        String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + uuid;

        String capStr = null, code = null;
        BufferedImage image = null;

        // 生成验证码
        String captchaType = RuoYiConfig.getCaptchaType();
        if ("math".equals(captchaType))
        {
            String capText = captchaProducerMath.createText();
            capStr = capText.substring(0, capText.lastIndexOf("@"));
            code = capText.substring(capText.lastIndexOf("@") + 1);
            image = captchaProducerMath.createImage(capStr);
        }
        else if ("char".equals(captchaType))
        {
            capStr = code = captchaProducer.createText();
            image = captchaProducer.createImage(capStr);
        }

        redisCache.setCacheObject(verifyKey, code, Constants.CAPTCHA_EXPIRATION, TimeUnit.MINUTES);
        // 转换流信息写出
        FastByteArrayOutputStream os = new FastByteArrayOutputStream();
        try
        {
            ImageIO.write(image, "jpg", os);
        }
        catch (IOException e)
        {
            return AjaxResult.error(e.getMessage());
        }

        ajax.put("uuid", uuid);
        ajax.put("img", Base64.encode(os.toByteArray()));
        return ajax;
    }

    @PostMapping("/yzyh")
    public AjaxResult yzyh(@RequestBody LoginVo vo) throws IOException
    {
        AjaxResult ajax = AjaxResult.success();
        String un = vo.getUn();
        String sbh = vo.getSbh();
        String sbCode = vo.getSbCode();
        SysUser user =iSysUserService.selectUserByUserName(new String(Base64.decode(un)));
        if(user!=null){
            int sbs = kSbhMapper.countTs(user.getUserId().toString());
            if(sbs<=100){
                ajax.put("id",user.getUserId());
                KSbh sbh1 =ikSbhService.selectKSbhByUidAndSbh(user.getUserId().toString(),sbh);
                if(sbh1==null){
                    sbh1 = new KSbh();
                    sbh1.setCreaterTime(new Date());
                    sbh1.setSbh(sbh);
                    sbh1.setSbCode(sbCode);
                    sbh1.setUserId(user.getUserId().toString());
                    ikSbhService.insertKSbh(sbh1);
                }
            }else{
                ajax = AjaxResult.error("设备数已达上限");
            }
        }else{
            ajax = AjaxResult.error("错误");
        }
        return ajax;
    }



    @GetMapping("/mytest")
    public void test(){
//        NextStepBean searchNextStepBean = new NextStepBean("执行搜索",TopSearchStep.class,3,2000,null,null);
//        NextStepBean inputNextStepBean = new NextStepBean("输入搜索关键字",TopSearchStep.class,2,2000,"回力",searchNextStepBean);
//        NextStepBean clickSearchBtn = new NextStepBean("点击搜索按钮",TopSearchStep.class,1,3000,null,inputNextStepBean);
//        NextStepBean startDy = new NextStepBean("启动",StartStep.class,1,0,null,clickSearchBtn);
        WsSysMsg.sendMsg("1","{\"ac\":1,\"acNo\":\"1\",\"data\":{\"delay\":0,\"name\":\"启动\",\"next\":{\"delay\":3000,\"name\":\"点击搜索按钮\",\"next\":{\"delay\":2000,\"name\":\"输入搜索关键字\",\"next\":{\"delay\":2000,\"name\":\"执行搜索\",\"step\":3,\"tClass\":\"com.example.autotest.assists.step.dy.TopSearchStep\"},\"serviceData\":\"回力\",\"step\":2,\"tClass\":\"com.example.autotest.assists.step.dy.TopSearchStep\"},\"step\":1,\"tClass\":\"com.example.autotest.assists.step.dy.TopSearchStep\"},\"step\":1,\"tClass\":\"com.example.autotest.assists.step.dy.StartStep\"}}");
    }
}
